interface IItem {
  func: Function
  ctx?: any
}

class EventManager {
  private eventDic: Map<string, Array<IItem>> = new Map()
  on(eventName: string, func: Function, ctx?: any) {
    if (this.eventDic.has(eventName)) {
      this.eventDic.get(eventName).push({ func, ctx })
    } else {
      this.eventDic.set(eventName, [{ func, ctx }])
    }
  }
  off(eventName: string, func: Function) {
    if (this.eventDic.has(eventName)) {
      const index = this.eventDic.get(eventName).findIndex(item => item.func == func)
      index > -1 && this.eventDic.get(eventName).splice(index, 1)
    }
  }
  emit(eventName: string, ...params: any) {
    if (this.eventDic.has(eventName)) {
      this.eventDic.get(eventName).forEach(({ func, ctx }) => {
        ctx ? func.apply(ctx, params) : func(...params)
      })
    }
  }
  clear() {
    this.eventDic.clear()
  }
}
export default new EventManager()
